<template>
  <div
    ref="timeBar"
    class="video-time-bar-controller pointer"
    @touchstart.stop="onStart"
    @touchmove.stop="onMove"
    @touchend.stop="onEnd"
    @mousedown.stop="onStart"
    @mousemove.stop="onMove"
    @mouseup.stop="onEnd"
  ></div>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { useElementBounding, whenever } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { useVideoTimeBarStore } from '@/store/video-time-bar'
import { usePreventTouchmove } from '@/compositions/mobile/preventTouchmove'

const props = defineProps({
  active: { type: Boolean, default: true },
})

const videoTimeBarStore = useVideoTimeBarStore()
const { seek, clear, start, stop } = videoTimeBarStore
const { seeking } = storeToRefs(videoTimeBarStore)
const timeBar = ref(null)
const {
  left: timeBarLeft,
  right: timeBarRight,
  width: timeBarWidth,
  update: updateTimeBarBounding,
} = useElementBounding(timeBar)

usePreventTouchmove(timeBar)

const onStart = (event) => {
  start()
  // onSeek(event)
}

const onMove = (event) => {
  if (seeking === false) return
  onSeek(event)
}

const onEnd = () => {
  // console.log('end ..')
  stop()
}

function onSeek(evt) {
  const pageX = evt.pageX || evt.touches[0].pageX
  const x = Math.min(timeBarRight.value, Math.max(0, pageX - timeBarLeft.value))
  const rate = x / timeBarWidth.value
  seek(rate)
}

function onActive() {
  clear(onActive.timerId)
  onActive.timerId = setTimeout(updateTimeBarBounding, 500)
}
onActivated(onActive)
whenever(() => props.active, onActive, { immediate: true })
</script>

<style lang="scss" scoped>
.video-time-bar-controller {
  width: calc(100% - 2rem);
  height: 1.5rem;
  position: absolute;
  left: 1rem;
  bottom: 4.625rem;
}

.desktop {
  .video-time-bar-controller {
    bottom: 0;
  }
}
</style>
